import React from 'react';
import ReactDom from 'react-dom';
import './battle.scss';
import { api } from 'js/api/api';
import Button from 'views/component/button/button';
import utils from 'js/core/utils';
import './pro-bars.css';
import clientBattleHandle from './battleHandle';
import iconData from 'js/data/iconData';
import TweenOne from 'rc-tween-one';
import BezierPlugin from 'rc-tween-one/lib/plugin/BezierPlugin';
TweenOne.plugins.push(BezierPlugin);
let duration = 800;
let numberDuration = 1000;


class Main extends React.Component {
    constructor(props) {
        super(props)
        let data = props.data || {};
        this.state = {
            p1: data.p1 || [],
            p2: data.p2 || [],
            msgs: [],
            end: false,
            round: 1,
            paused1: true,
            paused2: true,
            moment1: null,
            moment2: null,
            attackPos: null, defendPos: null
        }
    }
    componentDidMount() {
        // api('testBattle', (err, data) => {
        //     let battleMsg = data.battleMsg;
        //     this.setState({ p1: battleMsg.p1, p2: battleMsg.p2 }, () => {
        //         this.initBattleInfo();
        //     });
        // })
        this.setState({ p1: this.state.p1, p2: this.state.p2 }, () => {
            this.initBattleInfo();
        });
    }
    componentWillUnmount() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }
    getHpWidth = (role) => {
        let hp = role.hp > 0 ? role.hp : 0;
        return (hp / role.maxHp * 100) + '%';
    }
    initBattleInfo = () => {
        let fightAttriTeam1 = [],
            fightAttriTeam2 = [],
            battleQueue = [],
            p1 = this.state.p1,
            p2 = this.state.p2,
            team1 = {
                team: fightAttriTeam1
            },
            team2 = {
                team: fightAttriTeam2
            };
        p1.forEach((fightAttri, index) => {
            if (fightAttri) {
                fightAttri.teamId = 1;
                fightAttri.myTeam = team1;
                fightAttri.enemyTeam = team2;
                fightAttri.pos = index;
                fightAttriTeam1.push(fightAttri);
                battleQueue.push(fightAttri);
            }
        });
        team1.aliveNumber = fightAttriTeam1.length;
        p2.forEach((fightAttri, index) => {
            if (fightAttri) {
                fightAttri.teamId = 2;
                fightAttri.myTeam = team2;
                fightAttri.enemyTeam = team1;
                fightAttri.pos = index;
                fightAttriTeam2.push(fightAttri);
                battleQueue.push(fightAttri);
            }
        });
        team2.aliveNumber = fightAttriTeam2.length;
        console.log(battleQueue)
        let battleQueueLen = battleQueue.length;
        this.battleData = {
            team1: team1,
            team2: team2,
            battleQueue: battleQueue,
            battleQueueLen: battleQueue.length,
            battleIndex: 0,
        };
        this.timer = setInterval(() => {
            let attacker = battleQueue[this.battleData.battleIndex];
            while (attacker.hp <= 0) {
                this.battleData.battleIndex += 1;
                attacker = battleQueue[this.battleData.battleIndex];
            }

            let enemyTeam = attacker.enemyTeam.team;
            let defender = this.calcHatred(enemyTeam);
            this.calcDamage(attacker, defender);
            if (defender.hp <= 0) {
                defender.alive = false;
                attacker.enemyTeam.aliveNumber -= 1;
                if (attacker.enemyTeam.aliveNumber === 0) {
                    clearInterval(this.timer);
                    this.timer = null;
                }
            }
            this.battleData.battleIndex += 1;
            if (this.battleData.battleIndex >= this.battleData.battleQueueLen) {
                this.battleData.battleIndex = 0;
            }
            this.setState({})
        }, 1000)
    }
    //计算仇恨
    calcHatred = (team) => {
        let value = [];
        let total = 0;
        team.forEach((element, index) => {
            if (element.hp > 0) {
                value.push(element.hatred);
                total += element.hatred;
            } else {
                value.push(0);
            }
        });

        let randNumber = Math.random();
        for (let i = 0; i < value.length; i++) {
            let hatredPer = value[i] / total;
            if (randNumber <= hatredPer) {
                return team[i];
            }
            randNumber -= hatredPer;
        }
    }
    //计算攻击
    calcDamage(attacker, defender) {
        let pdef = defender.pdef,
            attack = attacker.attack;
        let damage = Math.ceil(attack * attack / (pdef + attack)); //计算伤害
        defender.hp -= damage;
        // console.log(`attacker:${attacker.name}|hp:${attacker.hp};defender:${defender.name}|hp:${defender.hp};伤害:${damage}`)
        return damage;
    }
    leave = () => {
        this.props.close();
    }
    render() {
        let { p1, p2, msgs, round, end, paused1, paused2, attackPos, defendPos } = this.state;
        let msgNode = msgs.map((item, i) => {
            return <div key={i}>{item}</div>
        });

        return <div id="battle" className="flex-col">
            <div className="round-text">第{round}回合</div>
            <div className="flex inline-flex jc-around battleBody">
                <div className="team" ref="team1" onClick={this.animation}>
                    {p1.map((role, i) => {
                        if (role) {
                            return <div className="role" key={i}>
                                <div className={"hp-par"}>
                                    <div className="hp-content flex-center">
                                        <div className="hp-out">
                                            <div className="hp" style={{ width: this.getHpWidth(role) }}></div>
                                            <div className="hp-text">{role.hp}/{role.maxHp}</div>
                                        </div>
                                    </div>
                                    <div className="role-name flex-center">
                                        <div className={"icon fonts-" + iconData[role.templateId]}></div>
                                        {role.name}
                                    </div>
                                </div>
                            </div>
                        } else {
                            return <div className="role" key={i}></div>
                        }
                    })}
                </div>
                <div className="team" ref="team2">

                    {p2.map((role, i) => {
                        return <div className="role" key={i}>
                            <div className={"hp-par"}>
                                <div className="hp-content flex-center">
                                    <div className="hp-out">
                                        <div className="hp-text">{role.hp}/{role.maxHp}</div>
                                        <div className="hp" style={{ width: this.getHpWidth(role) }}></div>
                                    </div>
                                </div>
                                <div className="role-name">{role.name}</div>
                            </div>
                            {/* <div className="role-status">状态</div> */}
                        </div>
                    })}
                </div>
            </div>
            <div className="battleMsg  scroll-absolute text-center flex-g-1">
                <div className="battleMsgContent">
                    {msgNode}
                </div>
            </div>
            <div className="bottom flex-center">
                <div className="leave-button" onClick={this.leave}>离开</div>
            </div>
        </div>
    }
}

export default Main;